import React, { useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { Card } from 'antd';
import './FloatCard.css';

interface FloatCardProps {
  /** 是否处于浮动状态 */
  isFloating: boolean;
  /** 卡片内容 */
  children: ReactNode;
  /** 自定义样式 */
  style?: React.CSSProperties;
  /** 占位元素的最大高度，单位px */
  placeholderMaxHeight?: number;
  /** 卡片阴影，当isFloating为true时使用 */
  floatingShadow?: string;
  /** 卡片背景色 */
  backgroundColor?: string;
}

/**
 * 浮动卡片组件
 * 当isFloating为true时，卡片会浮动显示在父容器顶部，并有阴影效果
 * 同时在下方创建占位元素，防止其他元素上移
 */
const FloatCard: React.FC<FloatCardProps> = ({
  isFloating,
  children,
  style = {},
  placeholderMaxHeight = undefined,
  floatingShadow = '0px 6px 13px 0px rgba(89,95,93,0.1), 0px 23px 23px 0px rgba(89,95,93,0.09), 0px 53px 32px 0px rgba(89,95,93,0.05), 0px 94px 38px 0px rgba(89,95,93,0.01), 0px 147px 41px 0px rgba(89,95,93,0)',
  backgroundColor = '#F8F8F8'
}) => {
  // 容器元素引用
  const containerRef = useRef<HTMLDivElement>(null);
  // 占位元素的最小高度
  const [placeholderMinHeight, setPlaceholderMinHeight] = useState<number>(0);

  // 获取容器元素的高度并设置为占位元素的最小高度
  useEffect(() => {
    if (containerRef.current && !isFloating) {
      const containerHeight = containerRef.current.offsetHeight;
      setPlaceholderMinHeight(containerHeight);
    }
  }, [isFloating, children]);
  // 构建卡片样式 - 添加CSS过渡动画效果
  const cardStyle: React.CSSProperties = {
    background: backgroundColor,
    width: '100%',
    padding: '16px 16px 0',
    position: isFloating ? 'absolute' : 'relative',
    top: isFloating ? 0 : 'auto',
    zIndex: isFloating ? 20 : 'auto',
    boxShadow: isFloating ? floatingShadow : 'none',
    // 添加CSS过渡动画效果
    transition: 'all 0.2s ease',
    // 使用transform实现平滑缩放效果
    transform: isFloating ? 'translateY(0)' : 'translateY(0)',
    // 确保动画在状态切换时平滑过渡
    ...style
  };

  return (
    <div className="float-card-container" style={{ position: 'relative'}} ref={containerRef}>
      <Card style={cardStyle}>
        {children}
      </Card>
      {/* 优化占位元素的过渡效果 */}
      <div 
        className="float-card-placeholder"
        style={{
          height: isFloating ? 'auto' : 0,
          minHeight: isFloating ? placeholderMinHeight : 0,
          maxHeight: isFloating && placeholderMaxHeight ? placeholderMaxHeight : 'none',
          // 使用opacity代替visibility以实现平滑过渡
          opacity: isFloating ? 1 : 0,
          // 确保元素在动画期间保持可见
          visibility: 'visible',
          // 阻止点击事件
          pointerEvents: 'none',
          // 统一设置所有可过渡属性的过渡效果
          // transition: 'height 0.6s ease, opacity 0.6s ease, min-height 0.6s ease, max-height 0.6s ease'
        }}
      />
    </div>
  );
};

export default FloatCard;